using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Material.MaterialGroup;
using ProduceBasicData.Domain.Inventories;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using ProduceBasicData.Api.Services;
using DocumentFormat.OpenXml.EMMA;

namespace ProduceBasicData.Api.Application.Handler.Material.MaterialGroup
{
    /// <summary>
    /// 物料群组新增处理类
    /// </summary>
    public class CreateMaterialGroupHandler : IRequestHandler<CreateMaterialGroupCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<MaterialGroupModel> materialGroupRepository;
        private readonly IBaseRespository<GroupTypeDictionary> groupTypeRepository;
        private readonly IBaseRespository<CraftModel> craftRepository;
        private readonly IMapper mapper;
        private readonly ICodeRuleService codeRuleService;

        public CreateMaterialGroupHandler(
            IBaseRespository<MaterialGroupModel> materialGroupRepository,
            IBaseRespository<GroupTypeDictionary> groupTypeRepository,
            IBaseRespository<CraftModel> craftRepository,
            IMapper mapper,ICodeRuleService codeRuleService)
        {
            this.materialGroupRepository = materialGroupRepository;
            this.groupTypeRepository = groupTypeRepository;
            this.craftRepository = craftRepository;
            this.mapper = mapper;
            this.codeRuleService = codeRuleService;
        }

        public async Task<ApiResult<int>> Handle(CreateMaterialGroupCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                // 验证群组类型是否存在
                var groupType = await groupTypeRepository.GetModelAsync(request.GroupTypeId);
                if (groupType == null)
                {
                    result.Code = ApiEnum.Failed;
                    result.Msg = "群组类型不存在";
                    return result;
                }

                // 如果指定了默认工艺路线，验证其是否存在
                if (request.DefaultCraftId.HasValue)
                {
                    var craft = await craftRepository.GetModelAsync(request.DefaultCraftId.Value);
                    if (craft == null)
                    {
                        result.Code = ApiEnum.Failed;
                        result.Msg = "默认工艺路线不存在";
                        return result;
                    }
                }

                

                // 映射实体
                var entity = mapper.Map<MaterialGroupModel>(request);

                //编码
                if (string.IsNullOrEmpty(entity.MaterialNo))
                {
                    var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.Material.MaterialGroupModel");
                    if (!string.IsNullOrEmpty(code))
                    {
                        entity.MaterialNo = code;
                    }
                    else
                    {
                        entity.MaterialNo = $"WL{DateTime.Now:yyyyMMddHHmmss}";
                    }
                }

                entity.GroupType = groupType.GroupTypeName;
                entity.CreateName = request.CreateName;
                entity.CreateTime = DateTime.Now;

                // 设置默认工艺路线名称
                if (request.DefaultCraftId.HasValue)
                {
                    var craft = await craftRepository.GetModelAsync(request.DefaultCraftId.Value);
                    entity.DefaultCraftName = craft?.CraftName ?? string.Empty;
                }

                // 保存到数据库
                var id = await materialGroupRepository.AddAsync(entity);
                if (id > 0)
                {
                    result.Data = id;
                    result.Code = ApiEnum.Success;
                    result.Msg = "物料群组新增成功";
                }
                else
                {
                    result.Code = ApiEnum.Failed;
                    result.Msg = "物料群组新增失败";
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"物料群组新增异常：{ex.Message}";
            }

            return result;
        }
    }
}
